package com.kldy8.kldyw;

import android.app.Activity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.view.MenuItemCompat;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.kldy8.kldyw.filmfactory.company.CompanyActivity;
import com.kldy8.kldyw.filmfactory.dteam.DteamListActivity;
import com.kldy8.kldyw.filmfactory.equipment.DeviceActivity;
import com.kldy8.kldyw.filmfactory.shootingvenue.ShootingVenueActivity;
import com.kldy8.kldyw.logre.LoginActivity;
import com.kldy8.kldyw.model.WebViewJavascriptBridgeDataOrder;
import com.kldy8.kldyw.model.WebViewJavascriptBridgeOrder;
import com.kldy8.kldyw.release.util.DateUtil;
import com.kldy8.kldyw.release.vedio.VedioActivity;
import com.kldy8.kldyw.system.ServerApi;
import com.kldy8.kldyw.system.ServerCallBack;
import com.kldy8.kldyw.system.UrlBuilder;
import com.kldy8.kldyw.tools.ImageFilePath;
import com.kldy8.kldyw.web.AppWebUrl;
import com.kldy8.kldyw.web.MyJavaScriptInterface;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import cn.sharesdk.onekeyshare.OnekeyShare;
import okhttp3.Request;

public class MyWebActivity extends BaseActivity implements  MyJavaScriptInterface
{
    private static final String TAG = "MyWebActivity";
    private static final int VEDIO_REQUESTCODE = 2000;


    //原始地址
    private String originalurl;
    private WebView webView;

    private String nowUrl = "";

    private RelativeLayout reloadlayout;
    private RelativeLayout loadinglayout;
    private ImageView reload_img;

    private Button close_btn;

    MyHandler handler = new MyHandler();

    @Override
    protected void onResume()
    {
        super.onResume();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_web);
        Intent intent = getIntent();
        String loadUrl = intent.getStringExtra("url");
        originalurl = AppWebUrl.createUrl(loadUrl);
        Log.e("MyWebActivity originalurl----",loadUrl);
        init(loadUrl);


    }

    private void init(final String urlString)
    {
        loadinglayout = (RelativeLayout) findViewById(R.id.loadinglayout);
        reloadlayout = (RelativeLayout) findViewById(R.id.reloadlayout);
        reload_img = (ImageView) findViewById(R.id.reload_img);
        reload_img.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                loadinglayout.setVisibility(View.VISIBLE);
                String nowloadURL = AppWebUrl.createUrl(urlString);
                webView.loadUrl(nowloadURL);
            }
        });

        close_btn = (Button) findViewById(R.id.close_btn);
        close_btn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                    finish();
            }
        });
        //直播最后页面
        if (originalurl.contains("live_end"))
        {
            close_btn.setVisibility(View.VISIBLE);
        }
        webView = (WebView) findViewById(R.id.webView);
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.addJavascriptInterface(this, "WebViewJavascriptBridge");

        webView.setWebChromeClient(mWebChromeClient);

        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        webView.setWebViewClient(new WebViewClient()
        {
            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl)
            {
                // TODO Auto-generated method stub
                super.onReceivedError(view, errorCode, description, failingUrl);
                loadinglayout.setVisibility(View.GONE);
                reloadlayout.setVisibility(View.VISIBLE);
            }


            @Override
            public void onPageFinished(WebView view, String url)
            {
                super.onPageFinished(view, url);
                loadinglayout.setVisibility(View.GONE);
            }


            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url)
            {
                loadinglayout.setVisibility(View.GONE);
                // TODO Auto-generated method stub
                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                Log.e("this is  MyWebActivity my Url",url);
                if(url.contains("tel:")){
                    //意图：想干什么事
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_CALL);
                    //url:统一资源定位符
                    //uri:统一资源标示符（更广）
                    intent.setData(Uri.parse(url));
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    //开启系统拨号器
                    startActivity(intent);
//                    startActivity(intent);
                    return true;
                }
                nowUrl = url;
                String loadUrl = AppWebUrl.createUrl(url);
//                nowUrl = loadUrl;

                if (url.contains("10086"))
                {
                    onReceivedError( view, 500,
                            "fuck", url);
                    return true;
                }
                if (!url.contains("kldy")&&(!url.contains("http://192.168.1.200")))
                {
                    onReceivedError( view, 500,
                            "fuck", url);
                    return true;
                }
                if (url.equals(UrlBuilder.URL_BASE_API))
                {
                    finish();
                    return true;
                }
                if (url.contains(UrlBuilder.URL_BASE_API+"/index.php/user/login")||url.contains(UrlBuilder.URL_BASE_API+"/user/login"))
                {
                    Intent intent = new Intent();
                    intent.setClass(MyWebActivity.this, LoginActivity.class);
                    startActivityRightToLeft(intent);
                    String nowloadURL = AppWebUrl.createUrl(urlString);
                    webView.loadUrl(nowloadURL);
                    return true;
                }

                if (url.contains(UrlBuilder.URL_BASE_API+"/dteam/dteam_list"))
                {
                    Intent intent = new Intent();
                    intent.setClass(MyWebActivity.this, DteamListActivity.class);
                    startActivityRightToLeft(intent);
                    String nowloadURL = AppWebUrl.createUrl(urlString);
                    webView.loadUrl(nowloadURL);
                    return true;
                }

                if (url.contains(UrlBuilder.URL_BASE_API+"/place/place_list"))
                {
                    Intent intent = new Intent();
                    intent.setClass(MyWebActivity.this, ShootingVenueActivity.class);
                    startActivityRightToLeft(intent);
                    String nowloadURL = AppWebUrl.createUrl(urlString);
                    webView.loadUrl(nowloadURL);
                    return true;
                }

                if (url.contains("tel:"))
                {
                    Uri uri = Uri.parse(url);
                    Intent intent = new Intent(Intent.ACTION_DIAL, uri);
                    startActivity(intent);
                    return true;
                }

                if (url.contains(UrlBuilder.URL_BASE_API+"/device/device_list"))
                {
                    Intent intent = new Intent();
                    intent.setClass(MyWebActivity.this, DeviceActivity.class);
                    startActivityRightToLeft(intent);
                    String nowloadURL = AppWebUrl.createUrl(urlString);
                    webView.loadUrl(nowloadURL);
                    return true;
                }
                if (url.contains(UrlBuilder.URL_BASE_API+"/company/company_list"))
                {
                    String type = "15";
                    if (url.contains("type_id=15"))
                    {
                        type = "15";
                    }
                    if (url.contains("type_id=14"))
                    {
                        type = "14";
                    }
                    if (url.contains("type_id=16"))
                    {
                        type = "16";
                    }
                    if (url.contains("type_id=17"))
                    {
                        type = "17";
                    }
                    Intent intent = new Intent();
                    intent.putExtra("type_id",type);
                    intent.setClass(MyWebActivity.this, CompanyActivity.class);
                    startActivityRightToLeft(intent);
                    String nowloadURL = AppWebUrl.createUrl(urlString);
                    webView.loadUrl(nowloadURL);
                    return true;
                }

//                //发布剧本
//                if (url.contains(UrlBuilder.URL_BASE_API+"/script/add"))
//                {
//                    Intent intent = new Intent();
//                    intent.setClass(MyWebActivity.this, ScenarioActivity.class);
//                    startActivityRightToLeft(intent);
//                    return true;
//                }

//                //发布简历
//                if (url.contains(UrlBuilder.URL_BASE_API+"/job/person_form"))
//                {
//                    Intent intent = new Intent();
//                    intent.setClass(MyWebActivity.this, ReleaseResumeActivity.class);
//                    startActivityRightToLeft(intent);
//                    return true;
//                }

//                //发布资讯
//                if (url.contains(UrlBuilder.URL_BASE_API+"/news/add"))
//                {
//                    Intent intent = new Intent();
//                    intent.setClass(MyWebActivity.this, ReleaseInformationActivity.class);
//                    startActivityRightToLeft(intent);
//                    return true;
//                }

//                //寻求设备
//                if (url.contains(UrlBuilder.URL_BASE_API+"/device/form"))
//                {
//                    String type = "0";
//                    if (url.contains("type=0"))
//                    {
//                        type = "0";
//                    }
//                    if (url.contains("type=1"))
//                    {
//                        type = "1";
//                    }
//                    if (url.contains("type=3"))
//                    {
//                        type = "2";
//                    }
//                    Intent intent = new Intent();
//                    intent.putExtra("type",type);
//                    intent.setClass(MyWebActivity.this, ReleaseEquipmentActivity.class);
//                    startActivityRightToLeft(intent);
//                    return true;
//                }

//                //发布场地
//                if (url.contains(UrlBuilder.URL_BASE_API+"/place/form"))
//                {
//                    String type = "0";
//                    if (url.contains("type=0"))
//                    {
//                        type = "0";
//                    }
//                    if (url.contains("type=1"))
//                    {
//                        type = "1";
//                    }
//                    if (url.contains("type=3"))
//                    {
//                        type = "2";
//                    }
//                    Intent intent = new Intent();
//                    intent.putExtra("type",type);
//                    intent.setClass(MyWebActivity.this, ReleaseSiteActivity.class);
//                    startActivityRightToLeft(intent);
//                    return true;
//                }

                //附近
                if (url.contains(UrlBuilder.URL_BASE_API+"/detection/lists"))
                {
                    String nowloadURL = AppWebUrl.createUrl(url);
                    String mloadUrl = AppWebUrl.addLatLan(nowloadURL);
                    Log.e("mloadUrl",mloadUrl);
                    view.loadUrl(mloadUrl);
                }

                else
                {
                    String nowloadURL = AppWebUrl.createUrl(url);
                    view.loadUrl(nowloadURL);
                }
                return true;
            }
        });

        webView.loadUrl(urlString);
    }

    //改写物理按键——返回的逻辑
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if(keyCode== KeyEvent.KEYCODE_BACK)
        {
            if(webView.canGoBack())
            {
                webView.goBack();//返回上一页面
                return true;
            }
            else
            {
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId()) {
            case android.R.id.home:// 点击返回图标事件
                this.finish();
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public boolean onCreateOptionsMenu(Menu menu)
    {
                return super.onCreateOptionsMenu(menu);
    }
//        MenuInflater inflater = getMenuInflater();
//        inflater.inflate(R.menu.menu_film_factory, menu);
//        MenuItem menuItem = menu.findItem(R.id.action_search);//在菜单中找到对应控件的item
//        SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
//        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
//
//            public boolean onQueryTextSubmit(String query)
//            {
//                Log.e("tag",query);
//                Intent intent=new Intent(MyWebActivity.this,SearchActivity.class);  //方法1
//                Bundle bundle=new Bundle();
//                String[] languages=getResources().getStringArray(R.array.search_array);
//
//                bundle.putString(SearchActivity.TAG_ITEM,languages[0]);
//                bundle.putString(SearchActivity.TAG_KEY, query);
//                intent.putExtras(bundle);
//                startActivity(intent);
//                overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
//
//                return true;
//            }
//
//            public boolean onQueryTextChange(String newText)
//            {
//                return true;
//            }
//        });
//
//
//
//        Log.d("Tag", "menu create");
//        MenuItemCompat.setOnActionExpandListener(menuItem, new MenuItemCompat.OnActionExpandListener() {//设置打开关闭动作监听
//            @Override
//            public boolean onMenuItemActionExpand(MenuItem item)
//            {
//                Toast.makeText(MyWebActivity.this, "onExpand", Toast.LENGTH_LONG).show();
//                return true;
//            }
//
//            @Override
//            public boolean onMenuItemActionCollapse(MenuItem item)
//            {
//                Toast.makeText(MyWebActivity.this, "Collapse", Toast.LENGTH_LONG).show();
//                return true;
//            }
//        });
//        return super.onCreateOptionsMenu(menu);



    /**
     * Provides a hook for calling "alert" from javascript. Useful for
     * debugging your javascript.
     */
    final class MyWebChromeClient extends WebChromeClient {
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            Log.d("------------", message);
            result.confirm();
            return true;
        }
    }


    @Override
    @JavascriptInterface
    public void requestObjectCFromHtml(String order)
    {
        Log.e("tag","order.....:"+order);
        try
        {
            JSONObject orderObject = new JSONObject(order);
            Log.e("orderObject",orderObject.toString());
            WebViewJavascriptBridgeOrder webViewJavascriptBridgeOrder = WebViewJavascriptBridgeOrder.resolution(orderObject);
           checkOrder(webViewJavascriptBridgeOrder);
        }
        catch (Exception e)
        {
            Toast.makeText(this,getResources().getString(R.string.error_system),Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }

    private void checkOrder(WebViewJavascriptBridgeOrder webViewJavascriptBridgeOrder)
    {
        String action = webViewJavascriptBridgeOrder.action;

        if (action == null)
        {
            Toast.makeText(this,getResources().getString(R.string.error_system),Toast.LENGTH_LONG).show();
            return;
        }
        if (action.equals(WebViewJavascriptBridgeOrder.ACTION_LOGIN))
        {
            Intent intent = new Intent();
            intent.setClass(MyWebActivity.this, LoginActivity.class);
            startActivityRightToLeft(intent);
            return;
        }
        if (action.contains(WebViewJavascriptBridgeOrder.ACTION_TOLOGIN)){
            Intent intent = new Intent();
            intent.setClass(MyWebActivity.this, LoginActivity.class);
            startActivityRightToLeft(intent);
            handler.sendEmptyMessage(BACKTRACK);
            return;
        }
        if (action.equals(WebViewJavascriptBridgeOrder.ACTION_LOGOUT))
        {
            ServerApi.logout(SystemSet.getInstance().getToken(), new ServerCallBack() {
                @Override
                public void onError(Request request, Exception e)
                {
                    Log.e("error",e.getMessage());
                    Toast.makeText(getApplication(),"退出失败",Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onResponse(String response) throws JSONException
                {
                    Log.e("logout",response);
//                    recreate();
                    SystemSet.getInstance().clean(getApplication());
                    SystemSet.getInstance().removeAllCookie(webView);

                }
            });
            return;
        }
        if (action.equals(WebViewJavascriptBridgeOrder.ACTION_BACKTRACK))
        {
            if (webViewJavascriptBridgeOrder.data !=  null)
            {

                if (webViewJavascriptBridgeOrder.data.level > 0)
                {
                    Message message = new Message();
                    message.what = BACKTRACK;
                    Bundle bundle=new Bundle();
                    bundle.putInt("level", webViewJavascriptBridgeOrder.data.level);
                    message.setData(bundle);//bundle传值，耗时，效率低
                    handler.sendMessage(message);
                }
                else
                {
                    handler.sendEmptyMessage(BACKTRACK);
                }
            }
            else
            {
                handler.sendEmptyMessage(BACKTRACK);
            }
            return;
        }
        if (action.equals(WebViewJavascriptBridgeOrder.ACTION_SHARE))
        {
            //({'action':'Share',data:{'title':'标题','images':'http://www.kldy8.com/images/logo.png','description':'描述'}});
            try
            {
                WebViewJavascriptBridgeDataOrder data =  webViewJavascriptBridgeOrder.data;
                if (data != null)
                {
                    String title = data.title;
                    String images =  data.images;
                    String description =  data.description;
//                  String url = dataJSONObject.optString("url");
                    String url = nowUrl;
                    showShare(title,images,description,url);
                }
                else
                {
                    throw new Error();
                }

            }
            catch (Exception e)
            {
                e.printStackTrace();
                Toast.makeText(this,getResources().getString(R.string.error_system),Toast.LENGTH_LONG).show();
            }
            return;

        }
        if (action.equals(WebViewJavascriptBridgeOrder.ACTION_APPROVE))
        {
            //({'action':'Share',data:{'title':'标题','images':'http://www.kldy8.com/images/logo.png','description':'描述'}});
            try
            {
                WebViewJavascriptBridgeDataOrder data =  webViewJavascriptBridgeOrder.data;
                if (data != null)
                {
                    String reloadUrl =   data.url;
                    Message message = new Message();
                    message.what = APPROVE;
                    Bundle bundle=new Bundle();
                    bundle.putString("url", reloadUrl);
                    message.setData(bundle);//bundle传值，耗时，效率低
                    handler.sendMessage(message);

                }
                else
                {
                    throw new Error();
                }

            }
            catch (Exception e)
            {
                e.printStackTrace();
                Toast.makeText(this,getResources().getString(R.string.error_system),Toast.LENGTH_LONG).show();
            }
            return;

        }

        if (action.equals(WebViewJavascriptBridgeOrder.ACTION_SWITCHLOGIN))
        {
            Intent intent = new Intent();
            intent.setClass(MyWebActivity.this, LoginActivity.class);
            startActivityRightToLeft(intent);
            return;
        }

        if (action.equals(WebViewJavascriptBridgeOrder.ACTION_BUBLISHVIDEO))
        {
            Intent intent = new Intent();
            intent.setClass(MyWebActivity.this, VedioActivity.class);
            startActivityForResultRightToLeft(intent, VEDIO_REQUESTCODE); // 带返回结果的Intent,标志码是1
            return;
        }
    }

    private void showShare(String title, String images, String description, String url)
    {
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        // title标题，印象笔记、邮箱、信息、微信、人人网、QQ和QQ空间使用
        oks.setTitle(title);
        // titleUrl是标题的网络链接，仅在Linked-in,QQ和QQ空间使用
        oks.setTitleUrl(url);
        // text是分享文本，所有平台都需要这个字段
        oks.setText(description);
        //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
        oks.setImageUrl(images);
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl(url);
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
//        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getResources().getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl(url);

        // 启动分享GUI
        oks.show(this);
    }



    private WebChromeClient mWebChromeClient = new WebChromeClient()
    {


        // android 5.0 这里需要使用android5.0 sdk
        public boolean onShowFileChooser(
                WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {

            Log.d("TAG", "onShowFileChooser");
            if (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(null);
            }


            mFilePathCallback = filePathCallback;

            /**
             Open Declaration   String android.provider.MediaStore.ACTION_IMAGE_CAPTURE = "android.media.action.IMAGE_CAPTURE"
             Standard Intent action that can be sent to have the camera application capture an image and return it.
             The caller may pass an extra EXTRA_OUTPUT to control where this image will be written. If the EXTRA_OUTPUT is not present, then a small sized image is returned as a Bitmap object in the extra field. This is useful for applications that only need a small image. If the EXTRA_OUTPUT is present, then the full-sized image will be written to the Uri value of EXTRA_OUTPUT. As of android.os.Build.VERSION_CODES.LOLLIPOP, this uri can also be supplied through android.content.Intent.setClipData(ClipData). If using this approach, you still must supply the uri through the EXTRA_OUTPUT field for compatibility with old applications. If you don't set a ClipData, it will be copied there for you when calling Context.startActivity(Intent).
             See Also:EXTRA_OUTPUT
             标准意图，被发送到相机应用程序捕获一个图像，并返回它。通过一个额外的extra_output控制这个图像将被写入。如果extra_output是不存在的，
             那么一个小尺寸的图像作为位图对象返回。如果extra_output是存在的，那么全尺寸的图像将被写入extra_output URI值。
             */
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    //设置MediaStore.EXTRA_OUTPUT路径,相机拍照写入的全路径
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (Exception ex) {
                    // Error occurred while creating the File
                    Log.e("WebViewSetting", "Unable to create Image File", ex);
                }

                // Continue only if the File was successfully created
                if (photoFile != null)
                {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(photoFile));
                    System.out.println(mCameraPhotoPath);
                } else {
                    takePictureIntent = null;
                }
            }

            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image/*");
            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[]{takePictureIntent};
                System.out.println(takePictureIntent);
            } else {
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }



        //The undocumented magic method override
        //Eclipse will swear at you if you try to put @Override here
        // For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            Log.d("TAG", "openFileChooser1");

            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILECHOOSER_RESULTCODE);

        }

        // For Android 3.0+
        public void openFileChooser(ValueCallback uploadMsg, String acceptType)
        {
            Log.d("TAG", "openFileChooser2");
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            startActivityForResult(
                    Intent.createChooser(i, "Image Chooser"),
                    FILECHOOSER_RESULTCODE);
        }

        //For Android 4.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            Log.d("TAG", "openFileChooser3");

            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            startActivityForResult(Intent.createChooser(i, "Image Chooser"), MyWebActivity.FILECHOOSER_RESULTCODE);

        }
    };

    private File file;


    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("TAG", "onActivityResult");

        if (resultCode == RESULT_OK  && requestCode == VEDIO_REQUESTCODE)
        {
                webView.reload();
        }
       else if (requestCode == FILECHOOSER_RESULTCODE)
        {
            if (null == mUploadMessage) return;
            Uri result = data == null || resultCode != RESULT_OK ? null
                    : data.getData();
            if (result != null) {
                String imagePath = ImageFilePath.getPath(this, result);
                if (imagePath!= null&& imagePath.length()>0) {
                    result = Uri.parse("file:///" + imagePath);
                }
            }
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        }
        else if (requestCode == INPUT_FILE_REQUEST_CODE && mFilePathCallback != null)
        {
            // 5.0的回调
            Uri[] results = null;

            // Check that the response is a good one
            if (resultCode == Activity.RESULT_OK) {
                if (data == null) {
                    // If there is not data, then we may have taken a photo
                    if (mCameraPhotoPath != null) {
                        Log.e("camera_photo_path", mCameraPhotoPath);
                        results = new Uri[]{Uri.parse(mCameraPhotoPath)};
                    }
                } else {
                    String dataString = data.getDataString();
                    Log.e("camera_dataString", dataString);
                    if (dataString != null) {
                        results = new Uri[]{Uri.parse(dataString)};
                    }
                }
            }

            mFilePathCallback.onReceiveValue(results);
            mFilePathCallback = null;
        } else {
            super.onActivityResult(requestCode, resultCode, data);
            return;
        }
    }


    public static final int INPUT_FILE_REQUEST_CODE = 1;
    private ValueCallback<Uri> mUploadMessage;
    private final static int FILECHOOSER_RESULTCODE = 2;

    private ValueCallback<Uri[]> mFilePathCallback;
    private String mCameraPhotoPath;



    //在sdcard卡创建缩略图
    //createImageFileInSdcard
//    @SuppressLint("SdCardPath")
    private File createImageFile() {
        //mCameraPhotoPath="/mnt/sdcard/tmp.png";
        File file=new File(Environment.getExternalStorageDirectory()+"/","tmp.png");
        mCameraPhotoPath=file.getAbsolutePath();
        if(!file.exists())
        {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    final int BACKTRACK = -10088;
    final int APPROVE = -10089;


    class MyHandler extends Handler
    {
        public MyHandler() {
        }

        // 子类必须重写此方法,接受数据
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            Log.d("MyHandler", "handleMessage......");
            super.handleMessage(msg);
            switch (msg.what)
            {
                case  BACKTRACK:
                    if (msg.getData().isEmpty())
                    {
                        goBackOrFinish(1);
                    }
                    else
                    {
                        int level =  msg.getData().getInt("level");
                        Log.d("BACKTRACK_LEVEL",""+level );
                        goBackOrFinish(level);
                    }
                    break;
                case  APPROVE:
                    if (msg.getData().isEmpty())
                    {
                        goBackOrFinish(1);
                    }
                    else
                    {
                        String url =  msg.getData().getString("url");
                        Log.d("APPROVE",""+url );
                        String appurl  = AppWebUrl.createUrl(url);
                        webView.loadUrl(appurl);
                    }
                    break;

            }
        }
    }

    private void goBackOrFinish(int degree)
    {
        while(degree > 0)
        {
            degree --;
            if (webView.canGoBack())
            {
                webView.goBack();//返回上一页面
            }
            else
            {
                finish();
            }
          }
    }



}
